package com.zhenwei.zscm.service;

import cn.hutool.core.util.StrUtil;
import com.zhenwei.zscm.common.base.RestMsg;
import com.zhenwei.zscm.common.base.RestResult;
import com.zhenwei.zscm.common.base.UserContext;
import com.zhenwei.zscm.common.exception.CustomException;
import com.zhenwei.zscm.common.utils.Utils;
import com.zhenwei.zscm.model.dto.order.OrderProductDTO;
import com.zhenwei.zscm.model.dto.order.OrderProductRepairDTO;
import com.zhenwei.zscm.model.enums.RepairStateEnum;
import com.zhenwei.zscm.model.vo.orderProductRepair.OrderProductRepairVO;
import com.zhenwei.zscm.repo.LogRepo;
import com.zhenwei.zscm.repo.OrderProductRepairRepo;
import com.zhenwei.zscm.repo.OrderProductRepo;
import com.zhenwei.zscm.repo.OrderRepo;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

@Service
@AllArgsConstructor
public class OrderProductRepairService {
    private OrderRepo orderRepo;
    private OrderProductRepo orderProductRepo;
    private OrderProductRepairRepo orderProductRepairRepo;
    private LogRepo logRepo;
    private final String LOG_TYPE = "售后工单维修";

    public RestResult create(OrderProductRepairVO vo){
        // 检查工单状态，如果不允许，则阻止
        String checkMsg = orderRepo.checkOrderStatus(vo.getOrderId());
        if (!"".equals(checkMsg)) {
            return RestResult.fail(checkMsg);
        }
        OrderProductDTO orderProduct = orderProductRepo.get(vo.getOrderId(), vo.getProductSn());
        if (orderProduct == null) {
            return RestResult.fail(RestMsg.ORDER_PRODUCT_NOT_EXISTS);
        }
        // 检查权限及状态
        if(UserContext.isNotAdmin() && orderProduct.getRepairStateCode().equals(RepairStateEnum.REPAIRED.name())) {
            return RestResult.fail(RestMsg.ORDER_PRODUCT_REPAIRED);
        }
        // 检查是否已经提交过维修数据
        OrderProductRepairDTO repairDetail = orderProductRepairRepo.detail(vo.getOrderId(), vo.getProductSn());
        if (repairDetail != null) {
            return RestResult.fail(RestMsg.ORDER_PRODUCT_REPAIR_EXISTS);
        }
        // 检查数据
        if("是".equals(vo.getPayState())) {
            if(StrUtil.isBlank(vo.getPayTypeCode())){
                return RestResult.fail(RestMsg.PAY_TYPE_IS_EMPTY);
            }
            if(vo.getPayDate() == null) {
                return RestResult.fail(RestMsg.PAY_DATE_IS_EMPTY);
            }
        } else {
            if(StrUtil.isBlank(vo.getPayTypeCode())){
                vo.setPayType("");
                vo.setPayTypeCode("");
            }
            if(vo.getPayDate() == null) {
                vo.setPayDate(Utils.DefaultDate());
            }
        }
        if(vo.getIsInvoice() != null && vo.getIsInvoice()) {
            if(StrUtil.isBlank(vo.getInvoiceTypeCode())) {
                return RestResult.fail(RestMsg.INVOICE_TYPE_IS_EMPTY);
            }
            if(StrUtil.isBlank(vo.getInvoiceNumber())){
                return RestResult.fail(RestMsg.INVOICE_NUMBER_IS_EMPTY);
            }
            if(vo.getInvoiceDate() == null) {
                return RestResult.fail(RestMsg.INVOICE_DATE_IS_EMPTY);
            }
        } else {
            if(StrUtil.isBlank(vo.getInvoiceTypeCode())) {
                vo.setInvoiceType("");
                vo.setInvoiceTypeCode("");
            }
            if(StrUtil.isBlank(vo.getInvoiceNumber())){
                vo.setInvoiceNumber("");
            }
            if(vo.getInvoiceDate() == null) {
                vo.setInvoiceDate(Utils.DefaultDate());
            }
        }
        // 保存
        boolean created = orderProductRepairRepo.create(vo);
        if (!created) {
            return RestResult.fail(RestMsg.FAILURE);
        }
        // 将维修状态同步到产品表
        boolean updated = orderProductRepo.updateState(vo.getOrderId(), vo.getProductSn(), vo.getRepairStateCode());
        if (!updated) {
            throw new CustomException(RestMsg.FAILURE);
        }
        boolean allRepaired = orderProductRepo.checkAllProductRepaired(vo.getOrderId());
        if(!allRepaired){
            return RestResult.success();
        }
        // 完成工单
        updated = orderRepo.finishOrder(vo.getOrderId());
        if (!updated) {
            throw new CustomException(RestMsg.FAILURE);
        }

        logRepo.createAsync(LOG_TYPE, "添加维修数据->"+vo);
        return RestResult.success();
    }

    public RestResult update(OrderProductRepairVO vo) {
        // 检查工单状态，如果不允许，则阻止
        String checkMsg = orderRepo.checkOrderStatus(vo.getOrderId());
        if (!"".equals(checkMsg)) {
            return RestResult.fail(checkMsg);
        }
        OrderProductDTO orderProduct = orderProductRepo.get(vo.getOrderId(), vo.getProductSn());
        if (orderProduct == null) {
            return RestResult.fail(RestMsg.ORDER_PRODUCT_NOT_EXISTS);
        }
        // 检查权限及状态
        if(UserContext.isNotAdmin() && orderProduct.getRepairStateCode().equals(RepairStateEnum.REPAIRED.name())) {
            return RestResult.fail(RestMsg.ORDER_PRODUCT_REPAIRED);
        }
        // 检查是否已经提交过维修数据
        OrderProductRepairDTO repairDetail = orderProductRepairRepo.detail(vo.getOrderId(), vo.getProductSn());
        if (repairDetail == null) {
            return RestResult.fail(RestMsg.ORDER_PRODUCT_REPAIR_NOT_EXISTS);
        }
        // 检查数据
        if("是".equals(vo.getPayState())) {
            if(StrUtil.isBlank(vo.getPayTypeCode())){
                return RestResult.fail(RestMsg.PAY_TYPE_IS_EMPTY);
            }
            if(vo.getPayDate() == null) {
                return RestResult.fail(RestMsg.PAY_DATE_IS_EMPTY);
            }
        } else {
            if(StrUtil.isBlank(vo.getPayTypeCode())){
                vo.setPayType("");
                vo.setPayTypeCode("");
            }
            if(vo.getPayDate() == null) {
                vo.setPayDate(Utils.DefaultDate());
            }
        }
        if(vo.getIsInvoice() != null && vo.getIsInvoice()) {
            if(StrUtil.isBlank(vo.getInvoiceTypeCode())) {
                return RestResult.fail(RestMsg.INVOICE_TYPE_IS_EMPTY);
            }
            if(StrUtil.isBlank(vo.getInvoiceNumber())){
                return RestResult.fail(RestMsg.INVOICE_NUMBER_IS_EMPTY);
            }
            if(vo.getInvoiceDate() == null) {
                return RestResult.fail(RestMsg.INVOICE_DATE_IS_EMPTY);
            }
        } else {
            if(StrUtil.isBlank(vo.getInvoiceTypeCode())) {
                vo.setInvoiceType("");
                vo.setInvoiceTypeCode("");
            }
            if(StrUtil.isBlank(vo.getInvoiceNumber())){
                vo.setInvoiceNumber("");
            }
            if(vo.getInvoiceDate() == null) {
                vo.setInvoiceDate(Utils.DefaultDate());
            }
        }
        boolean updated = orderProductRepairRepo.update(vo);
        if (!updated) {
            throw new CustomException(RestMsg.FAILURE);
        }
        // 将维修状态同步到产品表
        updated = orderProductRepo.updateState(vo.getOrderId(), vo.getProductSn(), vo.getRepairStateCode());
        if (!updated) {
            throw new CustomException(RestMsg.FAILURE);
        }
        boolean allRepaired = orderProductRepo.checkAllProductRepaired(vo.getOrderId());
        if(!allRepaired){
            return RestResult.success();
        }
        // 完成工单
        updated = orderRepo.finishOrder(vo.getOrderId());
        if (!updated) {
            throw new CustomException(RestMsg.FAILURE);
        }
        logRepo.createAsync(LOG_TYPE, "修改维修数据->"+vo);
        return RestResult.success();
    }

    public RestResult detail(String orderId, String productSn) {
        OrderProductRepairDTO detail = orderProductRepairRepo.detail(orderId, productSn);
        return RestResult.success(detail, 0);
    }
}
